package com.wteam.exception;

import com.wteam.untils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHanderler extends runtimeException {
    @ExceptionHandler(Exception.class)
    public Result ex(Exception ex) {
        ex.printStackTrace();
        return Result.error("程序运行异常，请联系管理员");
    }

    @ExceptionHandler(RuntimeException.class)
    public Result ex1(Exception ex) {
        ex.printStackTrace();
        return Result.error("程序运行异常，请联系管理员");
    }

    @ExceptionHandler(SQLIntegrityConstraintViolation.class)
    public Result SQLIntegrityConstraintViolation(SQLIntegrityConstraintViolation ex) {
        ex.printStackTrace();
        if (ex.getMessage().contains("Duplicate entry")){
            String[]split=ex.getMessage().split(" ");
            String msg=split[2]+"已存在";
            return Result.error(msg);

        }
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result SQLIntegrityConstraintViolation(BindException ex) {
        ex.printStackTrace();
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);

        });
        String errorMessage = null;
        for (Map.Entry<String, String> entry : errors.entrySet()) {
            errorMessage = entry.getValue();
        }
        return Result.error(errorMessage);
    }

    @ExceptionHandler(JwtException.class)
    public Result JwtException(JwtException ex) {
        ex.printStackTrace();
        return Result.token(ex.getMessage());
    }
    @ExceptionHandler(orderException.class)
    public Result orderException(orderException ex) {
        ex.printStackTrace();
        return Result.error(ex.getMessage());
    }


}
